<template>
  <div class="media-center">
    <el-container>
        <el-aside width="240px" class="leftMain">
          <div class="main-title">{{ $t('目录管理') }}</div>
          <media-menu-tree
                :tree-data="treeData"
                :tree-loading="treeLoading"
                :default-checked-keys="defaultCheckedKeys"
                :default-expanded-keys="defaultExpandedKeys"
                :context-menu-data="contextMenuData"
                :is-can-check="false"
                @currentNodeData="currentNodeDataChange"
                :api-obj="menuApiObj"
                :api-type="'2'" />
        </el-aside>
        <el-main class="rightMain">
          <el-tabs class="rightMain-tabs" style="height: 44px" v-model="activeName2">
            <el-tab-pane :label="$t('缩略图')" name="first"></el-tab-pane>
            <el-tab-pane :label="$t('详细信息')" name="second"></el-tab-pane>
          </el-tabs>
          <bs-main height="calc(100% - 44px)">
            <condition-row
              slot="header"
              @add="(data) => handCondition('add', data)"
              @action="(data) => handCondition('action', data)"
              @del="handCondition('del')"
              @edit="handCondition('edit')"
              @refresh="handCondition('refresh')"
              @search="(data) => handCondition('search', data)"
              ></condition-row>
            <pagination slot="footer" :total="pageData.total" :page="pageData.page" :limit="pageData.limit" :showAllChecked="true" :allChecked="allSize" @all="handleChangeAllSize" @pagination="doList"></pagination>
            
            <div style="margin-left: -15px;" v-show="activeName2 === 'first'">
              <mini-panel
                ref="miniPanel"
                class="center"   
                :datas="mediaData"
                @dbClick="_openPreview" />
            </div>
            <list
              height="calc( 100% - 15px )"
              ref="list"
              class="center"
              v-show="activeName2 === 'second'"
              :table-tag="tableName"
              :list-data="mediaData"
              :has-select="true"
              :list-cols="listCols"
              :init-cols-props.sync="initColsProps"
              :init-headmune-flag="initHeadmuneFlag"
              :action-opts="actionOpts"
              @sort="handleSort"
              @init-table="initTable"
              @editClick="handleEditClick"
              @delClick="handleDelClick"
              @filter="handleFilter"
              @cell-double-click="_openPreview">
              <template slot="auditStateSlot" slot-scope="{row}">
                {{ row.auditState | auditStateFilter(te) }}
              </template>
              <template slot="validitySlot" slot-scope="{row}">
                {{ row.validity | validityFilter(te) }}
              </template>
            </list>
          </bs-main>
        </el-main>
    </el-container>
    <template-dialog :visible.sync="templateDialog.show"></template-dialog>
    <preview-dialog :visible.sync="previewDialog.show" :pre-data="preData" :is-show-type="false"></preview-dialog>
    <examine-dialog :visible.sync="examineDialog.show" @examine="doExamine"></examine-dialog>
    <backgroud-choiceDialog :visible.sync="examineDialog.show"></backgroud-choiceDialog>
  </div>
</template>

<script>
import MediaMenuTree from '../components/MediaMenuTree'
import MiniPanel from '../components/MiniPanel'
import List from '@/components/List'
import Pagination from '@/components/Pagination'
import ConditionRow from './components/MediaTempCondition'
import TemplateDialog from './components/TemplateDialog'
import PreviewDialog from '../components/PreviewDialog'
import ExamineDialog from '../components/ExamineDialog'
import BackgroudChoiceDialog from './components/BackgroudChoiceDialog';
import MediaApi from '@/api/media'

import { createNamespacedHelpers } from 'vuex'
const {mapGetters, mapActions} = createNamespacedHelpers('media')

export default {
  components: {
    MediaMenuTree,
    MiniPanel,
    List,
    Pagination,
    ConditionRow,
    TemplateDialog,
    PreviewDialog,
    ExamineDialog,
    BackgroudChoiceDialog
  },
  name: 'media-template',
  data() {
    const headerContextMenus = {
      width: '120px',
      items: [
        'sortUp',
        'sortDown',
        'line',
        'cols'
      ]
    }
    return {
      initHeadmuneFlag: false,
      tableName:'mediaTemplate',
      templateDialog: {
        show: true
      },
      previewDialog: {
        show: false
      },
      examineDialog: {
        show: false
      },
      activeName: 'first',
      activeName2: 'first',
      treeLoading: false,
      treeData: [],
      defaultCheckedKeys: [],
      defaultExpandedKeys: [-1, -2],
      contextMenuData: [],
      mediaData: [],
      listCols: [
        {label: '名称', prop: 'name', headerContextMenus, minwidth: 120},
        {label: '类型', prop: 'type', headerContextMenus, minwidth: 120},
        {label: '审核', prop: 'auditState', headerContextMenus, minwidth: 90, slot: true},
        {label: '宽', prop: 'width', headerContextMenus, minwidth: 80},
        {label: '高', prop: 'height', headerContextMenus, minwidth: 80},
        {label: '被使用', prop: 'refCount', headerContextMenus, minwidth: 80},
        {label: '有效性', prop: 'validity', headerContextMenus, minwidth: 80, slot: true},
        {label: '修订号', prop: 'revision', headerContextMenus, minwidth: 80},
        {label: '创建时间', prop: 'createdAt', headerContextMenus, minwidth: 150},
      ],
      initColsProps: ['name', 'type', 'auditState', 'width', 'height', 'refCount', 'validity', 'revision', 'createdAt'],
      pageData: {
        page: 1,
        total: 0,
        limit: 15
      },
      queryData: {
        folderId: 0,
        orderType: 9,
        orderParam: 'desc'
      },
      menuApiObj: {
        get: MediaApi.getCatalogue,
        add: MediaApi.saveCatalogue,
        update: MediaApi.updateCatalogue,
        del: MediaApi.delCatalogue,
        bottomGet: MediaApi.getFollow,
        getOtherMedia: MediaApi.getOtherMedia
      },
      actionOpts: {
        name:'操作',
        show: true,
        align: 'center',
        width: '120px'
      },
      preData: {},
      folderId: 0,
      isOtherMenu: false,
      allSize: false
    }
  },
  filters: {
    auditStateFilter(val,te) {
      let msg = ''
      switch(val){
        case 0:
          msg = te('待审核')
          break
        case 1:
          msg = te('已通过')
          break
        case -1:
          msg = te('已拒绝')
          break
      }
      return msg
    },
    validityFilter(val,te) {
      if(val) {
        return te('有效')
      }
      return te('无效')
    }
  },
  created () {
    this.$eventBus.$on('doSaveTemplate', this.doSaveTemplate)
    if (!this.$_has('MEDIA_TEMPLATE_DELETE') && !this.$_has('MEDIA_TEMPLATE_UPDATE')) {
      this.actionOpts = {
        show: false
      }
    } else {
      this.actionOpts = {
        ...this.actionOpts,
        hidEditBtn: !this.$_has('MEDIA_TEMPLATE_UPDATE'),
        hidDelBtn: !this.$_has('MEDIA_TEMPLATE_DELETE')
      }
    }
  },
  beforeDestroy() {
    this.$eventBus.$off('doSaveTemplate')
  },
  computed:{
    ...mapGetters(['needFetchingList']),
    needFetching() {
      return this.needFetchingList('template')
    }
  },
  watch: {
    needFetching(v) {
      if (v) {
        this.doList()
        this.clearNeedFetcing({change: 'template'})
      }
    }
  },
  methods: {
    ...mapActions(['clearNeedFetcing', 'setNeedFetching']),
    initTable(config){
      this.initHeadmuneFlag = true
    },
    // 查询列表
    async doList(current) {
      if(current) {
        this.pageData = {
          ...this.pageData,
          ...current
        }
      }
      var queryData = this.$data.queryData
      queryData.current = this.pageData.page
      queryData.size = this.pageData.limit
      queryData.folderId = this.queryData.folderId
      if(this.queryData.queryType === '') {
        queryData.queryType = '0'
      }
      const res = await MediaApi.loadTemplate(queryData)
      if(res) {
        this.mediaData = res.records.map(item => {
          item.showType = 'template'
          return item
        })
        this.pageData.total = Number(res.total? res.total: 0)
      }
    },
    // 存储模板
    async doSaveTemplate(saveData) {
      let res = null
      if(saveData.id && saveData.id > 0) {
        res = await MediaApi.editTemplate(saveData)
      }else {
        res = await MediaApi.saveTemplate(saveData)
      }
      this.setNeedFetching({change: 'media'})
      this.doList({page:1})
      this.$eventBus.$emit('closeTemplateDialog')
      saveData.id && saveData.id > 0 ? this.$success('upd') : this.$success('add')
        
    },
    // 点击树菜单
    currentNodeDataChange(val) {
       this.isOtherMenu = !!val._isOther
      console.log('currentNodeDataChange -----------',val)
      if (val.id === -1 || val.id === -2) {
        this.folderId = val.id
        this.queryData.current = 1
        this.queryData.total = 0
        this.mediaData = []
        return
      }
      if(val.ownerUserId) {
        this.queryData.ownerUserId = val.ownerUserId
        this.queryData.folderId = val.id ? val.id : 0
        this.folderId = val.id ? val.id : 0
      } else {
        this.$delete(this.queryData, 'ownerUserId')
        this.queryData.folderId = val.id
        this.folderId = val.id
      }
      this.doList({page: 1})
    },
    async handleEditClick(row) {
      if (this._isSubOrOther()) return
      const res = await MediaApi.loadTemplateById({id:row.id })
      this.$eventBus.$emit('showTemplateDialog', res)
    },
    handleDelClick(row) {
      if (this._isSubOrOther()) return
      this._handleDel(row)
    },
    getActiveItem() {
      if (this.activeName2 === 'first') {
        return this.$refs.miniPanel.getActiveItem()
      } else {
        let items = this.$refs.list.getActiveItem()
        return items.length === 1 ? items[0] : items.length === 0 ? null : items
      }
    },
    _isSubOrOther() {
      if (this.folderId === -1 || this.folderId === -2 || this.isOtherMenu) {
        this.$alert('提示', '此目录不允许被操作')
        return true
      }
      return false
    },
    handCondition(type, data) {
      switch(type) {
        case 'add':
          if (this._isSubOrOther()) return
          this._openAddView(data)
          break;
        case 'action':
          this._handleAction(data)
          break;
        case 'del':
          if (this._isSubOrOther()) return
          this._handleDel(
            this.getActiveItem()
          )
          break;
        case 'edit':
          if (this._isSubOrOther()) return
          this._openEditView(
            this.getActiveItem()
          )
          break;
        case 'refresh':
          this._handleRefresh()
          break;
        case 'search': 
          this.queryData = {
            ...this.queryData,
            ...data
          }
          this.doList()
          break;
        default: console.log('未知操作');
      }
    },
    _handleAction(type) {
      switch(type) {
        case '预览':
          this._openPreview(
            this.getActiveItem()
          )
          break;
        case '审核':
          if (this._isSubOrOther()) return
          this._openExamine(
            this.getActiveItem()
          )
          break;
        case '另存为':
          if (this._isSubOrOther()) return
          this._openDownload(
            this.getActiveItem()
          )
          break;
        default:
      }
    },
    _handleRefresh() {
      this.doList({page:1})
      this.$message.success('刷新成功')
    },
    _openPreview(data) {
      if (!data) {
        this.$alert('提示', '请选择模板')
        return
      }
      if(data.length > 1) {
        this.$alert('提示', '此操作不支持多选')
        return
      }
      this.preData = data
      this.preData.showType = 2
      this.previewDialog.show = true
    },
    async _openEditView(data) {
      if (!data) {
        this.$alert('提示', '请选择模板')
        return
      }
      if(data.length > 1) {
        this.$alert('提示', '此操作不支持多选')
        return
      }
      const res = await MediaApi.loadTemplateById({id:data.id })
      this.$eventBus.$emit('showTemplateDialog', res)
    },
    _openExamine(file) {
      if(!this.allSize) {
        if (!file) {
          this.$alert('提示', '请选择模板')
          return
        }
        const obj = this.getActiveItem()
        let ids = []
        if(obj.length > 1) {
          obj.forEach(item => {
            if(item.auditState === 0) {
              ids.push(item.id)
            }
          })
        }else{
          if(obj.auditState === 0) {
            ids.push(obj.id)
          }
        }
        if(ids.length === 0) {
          this.$alert('提示', '已审核,不能操作')
          return
        }
      }
      this.examineDialog.show = true
    },
    async _openDownload(data) {
      let file = this.getActiveItem()
      if (!file) {
        this.$alert('提示', '请选择模板')
        return
      }
      if(data.length > 1) {
        this.$alert('提示', '此操作不支持多选')
        return
      }
      const res = await MediaApi.loadTemplateById({id: data.id })
      res.id = 0
      res.name = res.name? res.name.replace('.tpl', '') + '2' : ''
      this.$eventBus.$emit('showTemplateDialog', res)
    },
    async _handleDel(file) {
      if (!this.allSize && !file) {
        this.$alert('提示', '请选择模板')
        return
      }
      let ids = []
      if (!this.allSize) {
        if(file.length > 1) {
          file.forEach(item => {
            ids.push(item.id)
          })
        }else{
          ids.push(file.id)
        }
      }
      const confirm = await this.$confirm('提示', '是否确认删除？')
      if(confirm) {
        let queryData = {}
        if(this.allSize) {
          queryData = {
            ...this.queryData,
            allSize: this.allSize,
            total: this.pageData.total
          }
        }
        const res =  await MediaApi.deleteTemplate({ ids: ids, ...queryData })
        if(res) {
          this.setNeedFetching({change: 'media'})
          this.doList({page: 1})
          this.$success('del')
          this.allSize = false
        }
      }
    },
    _openAddView(type) {
      const templateFormData = {
        id: 0,
        folderId: this.queryData.folderId,
        ownerUserId: this.queryData.ownerUserId
      }
      this.$eventBus.$emit('showTemplateDialog', templateFormData)  
    },
    // 审核
    async doExamine(val, desc, cb) {
      let ids = []
      if(!this.allSize) {
        const obj = this.getActiveItem()
        if(obj.length > 1) {
          obj.forEach(item => {
            if(item.auditState === 0) {
              ids.push(item.id)
            }
          })
        }else{
          if(obj.auditState === 0) {
            ids.push(obj.id)
          }
        }
      }
      let queryData = {}
      if(this.allSize) {
        queryData = {
          ...this.queryData,
          allSize: this.allSize,
          total: this.pageData.total
        }
      }
      const params = queryData
      params.ids = ids
      params.auditState = val
      params.auditReason = desc
      try {
        const res = await MediaApi.examineTemplate(params)
        cb && cb()
        this.doList({page: 1})
        this.examineDialog.show = false
        this.allSize = false
        this.$success('exa')
        this.setNeedFetching({change: 'program'}) 
      } catch (error) {
        cb && cb(true)
      }
     
    },
    handleFilter(filterInfo) {
      console.log('filterInfo----', filterInfo)
    },
    // 排序
    handleSort(sortInfo) {
      console.log('name', 'type', 'auditState', 'check', 'width', 'height', 'refCount', 'validity', 'revision', 'createdAt', sortInfo)
      switch(sortInfo.prop) {
        case 'name':
          this.queryData.orderType = 1
          break;
        case 'type':
          this.queryData.orderType = 2
          break;
        case 'auditState':
          this.queryData.orderType = 3
          break;
        case 'width':
          this.queryData.orderType = 4
          break;
        case 'height':
          this.queryData.orderType = 5
          break;
        case 'refCount':
          this.queryData.orderType = 6
          break;
        case 'validity':
          this.queryData.orderType = 7
           break;
        case 'revision':
          this.queryData.orderType = 8
          break;
        case 'createdAt':
          this.queryData.orderType = 9
          break;
        default:
          this.$alert('提示', '系统不支持排序')
          return;
      }
      this.queryData.orderParam = sortInfo.type
      this.doList()
    },
    // 选择所有页
    handleChangeAllSize(val) {
      this.allSize = val
      this.$refs.list.clearSelection();
    },
    te(arg) {
      const hasKey = this.$te(arg)
      if (hasKey) {
        const result = this.$t(arg)
        return result
      }
      return arg
    }
  }
}
</script>

<style lang="scss" scoped>
// import '@/styles/bs-common.scss';

::v-deep .ctl-box {
  padding: 12px 0 12px 0 !important;
}
.leftMain >>> .el-tabs__content {
  padding-left: 0;
  padding-right: 0;
}
.leftMain {
  ::v-deep .el-tabs__item{padding:0 !important; width:125px; text-align:center;height: 44px; line-height: 44px;}
  ::v-deep .el-tabs__item:last-child{border-right:0 !important;}
}

.media-center .rightMain .el-tabs {
  border-bottom: 0;
}
.media-center .rightMain .el-tabs__content {
  padding: 0;
}
</style>
